package simulationStack;

import java.util.Arrays;
import java.util.Stack;

public class MyStack {
    private int[] elem;
    private int usedSize;//不初始化默认为 0

    private static final int DEFAULT_CAPACITY=10;

    public MyStack() {
        this.elem = new int[DEFAULT_CAPACITY];
    }

    public boolean isFull(){
        return usedSize==elem.length;
    }

    public void push(int val){
        if (isFull()){
            elem= Arrays.copyOf(elem,2*elem.length);
        }
        elem[usedSize]=val;
        usedSize++;
    }

    public boolean isEmpty(){
        return usedSize==0;
    }

    //出栈
    public int pop(){
        if(isEmpty()){
            throw new EmptyException();
        }
        int oldVal=elem[usedSize-1];
        usedSize--;
        return oldVal;
    }

    public int peek(){
        if(isEmpty()){
            throw new EmptyException();
        }
        return elem[usedSize-1];
    }

    public int size(){
        return usedSize;
    }


/*
    栈的应用场景   将递归转化为循环  比如：逆序打印链表
    1、递归方式
    void printList(Node head){
        if(head!=null){
            printList(head.next);
            System.out.print(head.val + " ");
        }
    }

    2、循环方式
    void printList(Node head){
        if(head==null){
            return;
        }
        Stack<Node> s = new Stack<>();
        // 将链表中的结点保存在栈中
        Node cur = head;
        while(cur!=null){
            s.push(cur);
            cur = cur.next;
        }
        // 将栈中的元素出栈
        while(!s.empty()){
            System.out.print(s.pop().val + " ");
        }
    }
*/

    public boolean IsPopOrder (int[] pushV, int[] popV) {
        Stack<Integer> stack=new Stack<>();
        int j=0;
        for (int i = 0; i < pushV.length; i++) {
            stack.push(pushV[i]);
            while (!stack.empty() && j < popV.length && stack.peek() == popV[j]) {
                stack.pop();
                j++;
            }
        }
        return stack.empty();
    }
}




















